# -*- coding: utf-8 -*-
# @Author: Administrator
# @Date:   2022-05-19 16:05:24
# @Last Modified by:   Administrator
# @Last Modified time: 2022-06-16 09:49:20
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

extreme_user_api = Blueprint('extreme_user_api', __name__)
extreme_user_down_api = Blueprint('extreme_user_down_api', __name__)
extreme_user_schedule_api = Blueprint('extreme_user_schedule_api', __name__)
extreme_user_schedule_down_api = Blueprint('extreme_user_schedule_down_api', __name__)

@extreme_user_api.route("/extreme_user_event_project", methods=['POST', 'GET'])
def project_action():
    update_data = json.loads(request.data)
    _type = update_data['type']
    project = update_data['project']

    result = {'msg': '成功', 'code': 200, 'data':[]}
    if project == -1:
        project_data = ExtremeUserEventProject.query.order_by('project').all()
    else:
        project_data = ExtremeUserEventProject.query.filter_by(project=project).first()

    if _type == 'index':
        for d in project_data:
            project = int(d.project)
            event_type = d.event_type
            tmp = {'project': project,
                   'remark': d.remark,
                   'event_type': event_type}
            result['data'].append(tmp)

    elif _type == 'remark':
        remark = str(update_data['remark'])
        project_data.remark = remark
        # ExtremeUserEventProject.query.filter_by(project=project).update({'remark': remark})
        db.session.commit()
        result = {'msg': 'remark成功', 'code': 0}

    elif _type == 'clone':
        new_project_data = ExtremeUserEventProject(
            remark=project_data.remark,
            basic=project_data.basic,
            rank=project_data.rank,
            event_type=project_data.event_type)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'code': 2}
        else:
            result = {'msg': '克隆成功', 'code': 0}
    
    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = ExtremeUserEventProject.query.filter_by(project=project).first()
        if new_project_data is None:
            result = {'msg': '删除成功', 'code': 0}
        else:
            result = {'msg': '删除失败', 'code': 1}
    
    elif _type == 'basic':
        result = {}
        basic_data = json.loads(project_data.basic)
        event_type = project_data.event_type

        # with open(STATIC_PATH + 'extreme_user_event_task.json', encoding='utf8') as f:
        #     extreme_user_event_task = json.load(f)

        extreme_user_event_task = []
        # 处理 task_pool {$id: $label}
        pool_map_label = {}
        pool_query = ExtremeUserTaskPool.query.order_by('id').all()
        for pool_que in pool_query:
            pool_id = pool_que.id
            pool_data = json.loads(pool_que.data)
            pool_label = pool_data['label']
            pool_map_label[str(pool_id)] = pool_label

        task_query = ExtremeUserScoreType.query.order_by('project').all()
        for task_que in task_query:
            task_id = task_que.project
            task_data = json.loads(task_que.data)
            task_score = task_data['score']
            task_target = task_data['target']
            task_pool_id = task_data['task_pool_id']

            label = pool_map_label[str(task_pool_id)]
            label = label.replace('x', str(task_target))
            label = '{0}-{1} [得{2}分]'.format(task_id,
                                               label,
                                               task_score)

            tmp = {'label': label, 'value': task_id}
            extreme_user_event_task.append(tmp)

        result['score_id_list'] = extreme_user_event_task
        result['data'] = basic_data
        result['event_type'] = event_type

    elif _type == 'update_basic':
        basic_data = update_data['data']
        project_data.basic = json.dumps(basic_data)
        project_data.event_type = update_data['event_type']
        db.session.commit()

    elif _type == 'rank':
        data = {}
        rank = json.loads(project_data.rank)
        cur_stage = str(update_data['cur_stage'])
        if cur_stage in rank:
            rank_stage = rank[cur_stage]
            for i in range(len(rank_stage['rank_reward'])):
                rank_stage['rank_reward'][i]['idx'] = i
            for v in rank_stage['goal'].values():
                for i in range(len(v)):
                    v[i]['idx'] = i
        else:
            # 删除了 '0'
            rank_list = []
            for k in rank.keys():
                rank_list.append(int(k))
            rank_stage = rank[str(min(rank_list))]
            for i in range(len(rank_stage['rank_reward'])):
                rank_stage['rank_reward'][i]['idx'] = i
            for v in rank_stage['goal'].values():
                for i in range(len(v)):
                    v[i]['idx'] = i

        rank_list = []
        rank_tabs = []
        total_rank_group = 0
        rank_tabIndex = 0,

        goal_list = []
        goal_tabs = []
        total_goal_group = 0,
        goal_tabIndex = 0

        for k, v in rank.items():
            rank_list.append(int(k))
        rank_list.sort()
        total_rank_group = max(rank_list)
        rank_tabIndex = len(rank_list)
        for i in range(len(rank_list)):
            rank_k = str(rank_list[i])
            tmp = {'title': '段位-{}'.format(i+1),
                   'name': rank_k}
            rank_tabs.append(tmp)

        for k, v in rank_stage['goal'].items():
            goal_list.append(int(k))
        goal_list.sort()
        total_goal_group = max(goal_list)
        goal_tabIndex = len(goal_list)
        for i in range(len(goal_list)):
            goal_k = str(goal_list[i])
            tmp = {'title': 'goal-档位 {}'.format(i+1),
                   'name': goal_k}
            goal_tabs.append(tmp)

        data['rank_stage'] = rank_stage
        data['rank_tabs'] = rank_tabs
        data['total_rank_group'] = total_rank_group
        data['rank_tabIndex'] = rank_tabIndex

        data['goal_tabs'] = goal_tabs
        data['total_goal_group'] = total_goal_group
        data['goal_tabIndex'] = goal_tabIndex

        result['data'] = data
        result['event_type'] = project_data.event_type

    elif _type == 'update_rank':
        rank_data = update_data['data']
        cur_stage = update_data['cur_stage']
        for node in rank_data['rank_reward']:
            if 'idx' in node:
                del node['idx']
        for v in rank_data['goal'].values():
            for node in v:
                if 'idx' in node:
                    del node['idx']
        rank = json.loads(project_data.rank)
        rank[str(cur_stage)] = rank_data
        project_data.rank = json.dumps(rank)
        db.session.commit()

    elif _type == 'add_rank':
        rank = json.loads(project_data.rank)
        rank_list = []
        for k in rank.keys():
            rank_list.append(int(k))
        max_rank_key = max(rank_list) + 1
        tmp = {'condition': [0, 0],
               'goal':{
                "0":[]
               },
               'rank_reward': []
               }
        rank[str(max_rank_key)] = tmp
        project_data.rank = json.dumps(rank)
        db.session.commit()

    elif _type == 'delete_rank':
        cur_stage = str(update_data['cur_stage'])
        rank = json.loads(project_data.rank)
        if cur_stage in rank:
            del rank[cur_stage]
        project_data.rank = json.dumps(rank)
        db.session.commit()

    elif _type == 'clone_rank':
        cur_stage = str(update_data['cur_stage'])
        clone_to_stage = str(update_data['clone_to_stage'])
        rank = json.loads(project_data.rank)
        cur_stage_data = rank[cur_stage]
        if clone_to_stage == '-1':
            rank_list = []
            for k in rank.keys():
                rank_list.append(int(k))
            max_rank_key = max(rank_list) + 1
            rank[str(max_rank_key)] = deepcopy(cur_stage_data)
            project_data.rank = json.dumps(rank)
        else:
            rank[str(clone_to_stage)] = deepcopy(cur_stage_data)
            project_data.rank = json.dumps(rank)
        db.session.commit()

    elif _type == 'score_type':
        score_map_pid = {}
        proj_query = ExtremeUserEventProject.query.order_by('project').all()
        for proj_que in proj_query:
            pid = str(proj_que.project)
            basic = json.loads(proj_que.basic)
            score_id_list = basic['score_id']
            for score_id in score_id_list:
                if str(score_id) not in score_map_pid:
                    score_map_pid[str(score_id)] = set()
                score_map_pid[str(score_id)].add(pid)

        task_pool = []
        pool_query = ExtremeUserTaskPool.query.order_by('id').all()
        for pool_que in pool_query:
            _id = pool_que.id
            pool_data = json.loads(pool_que.data)
            tmp = {'label': '{0}-{1}'.format(_id, pool_data['label']),
                   'value': _id}
            task_pool.append(tmp)

        query = ExtremeUserScoreType.query.order_by('project').all()
        res = []
        count = 1
        for que in query:
            pid = que.project
            data = json.loads(que.data)
            data['task_id'] = pid
            data['idx']: count
            count += 1
            if str(pid) in score_map_pid:
                data['used_pid'] = ','.join(score_map_pid[str(pid)])
            else:
                data['used_pid'] = ''
            res.append(data)

        result['data'] = res
        result['task_pool'] = task_pool

    elif _type == 'delete_score_type':
        task_id = update_data['task_id']
        score_que = ExtremeUserScoreType.query.filter_by(project=task_id).first()
        db.session.delete(score_que)
        db.session.commit()
        new_project_data = ExtremeUserScoreType.query.filter_by(project=task_id).first()
        if new_project_data is None:
            result = {'msg': '删除成功', 'code': 0}
        else:
            result = {'msg': '删除失败', 'code': 1}

    elif _type == 'update_score_type':
        score_list = update_data['data']
        for node in score_list:
            if 'idx' in node:
                del node['idx']
            if 'used_pid' in node:
                del node['used_pid']

            task_id = node['task_id']
            del node['task_id']
            if task_id == -1:
                new_node = ExtremeUserScoreType(data=json.dumps(node))
                db.session.add(new_node)
                db.session.commit()

            else:
                ExtremeUserScoreType.query.filter_by(
                    project=task_id).update({'data': json.dumps(node)})
                db.session.commit()

        result['msg'] = '更新成功'

    return jsonify(result) 

@extreme_user_down_api.route("/extreme_user_event_project_down/<int:is_push>", methods=['POST', 'GET'])
def DownAction(is_push):
    extreme_user_event_project = {}

    # with open(STATIC_PATH + 'extreme_user_event_task.json', encoding='utf-8') as f:
    #     content = json.load(f)
    #     score_type_list = content['value']

    query = ExtremeUserEventProject.query.order_by('project').all()
    for p in query:
        project_id = str(p.project)

        basic_data = json.loads(p.basic)
        rank = json.loads(p.rank)
        event_type = int(p.event_type)

        score_id_list = basic_data['score_id']

        basic = {}
        control = {}
        if event_type == 0:
            basic['event_theme'] = 0
            basic['event_type'] = 0
            basic['order'] = 1
            control['condition_type'] = 2
        elif event_type == 1:
            basic['event_theme'] = 5
            basic['event_type'] = 1
            basic['order'] = 2
            control['condition_type'] = 0
        elif event_type == 2:
            basic['event_theme'] = 0
            basic['event_type'] = 2
            basic['order'] = 3
            control['condition_type'] = 0

        calc_score = {"score_type_list":[]}

        for src_id in score_id_list:
            task_que = ExtremeUserScoreType.query.filter_by(project=src_id).first()
            task_data = json.loads(task_que.data)
            task_target = task_data['target']
            task_score = task_data['score']

            task_pool_id = task_data['task_pool_id']
            pool_que = ExtremeUserTaskPool.query.filter_by(id=task_pool_id).first()
            pool_data = json.loads(pool_que.data)
            tmp = [pool_data['doc_id'],
                   task_score*10000,
                   1,
                   pool_data['score_type'],
                   pool_data['score_map_id'],
                   pool_data['age'],
                   task_target*pool_data['target_unit'],
                   pool_data['target_unit']]
            calc_score['score_type_list'].append(tmp)
            # if str(src_node) in score_type_list:
            #     calc_score['score_type_list'].append(
            #         score_type_list[str(src_node)])

        # rank
        rank_list = []
        new_rank = []
        for k in rank.keys():
            rank_list.append(int(k))
        rank_list.sort()
        for x in rank_list:
            node = rank[str(x)]
            new_goal = []
            goal_list = []
            goal = node['goal']
            for goal_k in goal.keys():
                goal_list.append(int(goal_k))
            goal_list.sort()
            for goal_x in goal_list:
                goals = goal[str(goal_x)]
                for goal_node in goals:
                    goal_node['reward'] = RewardToTMysqlNew(goal_node['reward'])
                new_goal.append(goals)
            for reward_node in node['rank_reward']:
                reward_node['reward'] = RewardToTMysqlNew(reward_node['reward'])

            new_rank.append({'condition': node['condition'],
                             'goal': new_goal,
                             'rank_reward': node['rank_reward']})

        if project_id not in extreme_user_event_project:
            extreme_user_event_project[project_id] = {}

        extreme_user_event_project[project_id]['basic'] = basic
        extreme_user_event_project[project_id]['calc_score'] = calc_score
        extreme_user_event_project[project_id]['control'] = control
        extreme_user_event_project[project_id]['rank'] = new_rank

    response = DownLoad('event_project', extreme_user_event_project, is_push)

    return response



@extreme_user_schedule_api.route("/extreme_user_event_schedule", methods=['POST', 'GET'])
def schedule_action():
    update_data = json.loads(request.data)
    _type = update_data['type']
    project = update_data['project']

    result = {'msg': '成功', 'code': 200, 'data':[]}
    if project == -1:
        project_data = ExtremeUserEventSchedule.query.order_by('project').all()
    else:
        project_data = ExtremeUserEventSchedule.query.filter_by(project=project).first()

    if _type == 'index':
        for d in project_data:
            project = int(d.project)
            tmp = {'project': project,
                   'remark': d.remark}
            result['data'].append(tmp)

    elif _type == 'remark':
        remark = str(update_data['remark'])
        project_data.remark = remark
        # ExtremeUserEventProject.query.filter_by(project=project).update({'remark': remark})
        db.session.commit()
        result = {'msg': 'remark成功', 'code': 0}

    elif _type == 'clone':
        new_project_data = ExtremeUserEventSchedule(
            remark=project_data.remark + '_clone',
            basic=project_data.basic)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'code': 2}
        else:
            result = {'msg': '克隆成功', 'code': 0}
    
    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = ExtremeUserEventSchedule.query.filter_by(project=project).first()
        if new_project_data is None:
            result = {'msg': '删除成功', 'code': 0}
        else:
            result = {'msg': '删除失败', 'code': 1}
    
    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        new_pid_list = {}
        pid_list = read_s3_file('event_project')
        for key, value in pid_list.items():
            event_type = value['basic']['event_type']
            if str(event_type) not in new_pid_list:
                new_pid_list[str(event_type)] = []
            new_pid_list[str(event_type)].append({"label":"p_"+str(key), "value": int(key)})
        # new_pid_list[str(0)].append({"label":"p_"+str(1), "value": int(1)})     
        result['data'] = basic_data
        result['pid_list'] = new_pid_list

    elif _type == 'update_basic':
        basic_data = update_data['data']
        project_data.basic = json.dumps(basic_data)
        db.session.commit()
    return jsonify(result) 

@extreme_user_down_api.route("/extreme_user_event_schedule_down/<int:is_push>", methods=['POST', 'GET'])
def DownScheduleAction(is_push):
    event_default_schedule = {}

    query = ExtremeUserEventSchedule.query.order_by('project').all()
    for p in query:
        project_id = str(p.project)

        if project_id not in event_default_schedule:
            event_default_schedule[project_id] = {}

        basic_data = json.loads(p.basic)

        for event_type, value in basic_data.items():

            if str(event_type) not in event_default_schedule[project_id]:
                event_default_schedule[project_id][event_type] = []

            cycle = value['cycle']
            cycle_pid_list = value['cycle_pid_list']

            for i in range(len(cycle_pid_list)):
                forecast_time = i * cycle
                begin_time = forecast_time + 300
                end_time = forecast_time + cycle - 1
                pid =  cycle_pid_list[i]['pid']

                tmp = {
                    'forecast_time': forecast_time,
                    'begin_time': begin_time,
                    'end_time': end_time,
                    'pid': pid
                }
                event_default_schedule[project_id][event_type].append(tmp)
        
    response = DownLoad('event_default_schedule', event_default_schedule, is_push)

    return response